<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" v-show="showSearch" :inline="true"
      label-width="68px">
      <el-form-item label="人员姓名" prop="roleName">
        <el-input v-model="queryParams.roleName" placeholder="请输入人员姓名" clearable
          style="width: 240px" @keyup.enter="handleQuery" />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="Plus" @click="handleAdd"
          v-hasPermi="['role:add']">新增</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <!-- 表格数据 -->
    <el-table v-loading="loading" :data="roleList" :max-height="tableHeight">
      <el-table-column label="角色名称" prop="roleName" :show-overflow-tooltip="true" />
      <!-- <el-table-column label="权限字符" prop="roleVarchar" :show-overflow-tooltip="true" /> -->
      <el-table-column label="状态" align="center">
        <template #default="scope">
          <el-switch v-model="scope.row.roleStatue" :active-value="0" :inactive-value="1"
            @change="handleStatusChange(scope.row)"
            :disabled='scope.row.remark ==11?true:false'></el-switch>
        </template>
      </el-table-column>
      <el-table-column label="创建时间" align="center" prop="createTime">
        <template #default="scope">
          <span>{{ parseTime(scope.row.createTime) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="备注" prop="roleNote" :show-overflow-tooltip="true" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-tooltip content="修改" placement="top">
            <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)"
              v-hasPermi="['role:edit']" :disabled='scope.row.remark ==11?true:false'></el-button>
          </el-tooltip>
          <el-tooltip content="删除" placement="top">
            <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)"
              v-hasPermi="['role:delete']" :disabled='scope.row.remark ==11?true:false'></el-button>
          </el-tooltip>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total > 0" :total="total" v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize" @pagination="getList" />

    <!-- 添加或修改角色配置对话框 -->
    <el-dialog :title="title" v-model="open" width="500px" append-to-body
      :close-on-click-modal='false'>
      <el-form ref="roleRef" :model="form" :rules="rules" label-width="100px">
        <el-form-item label="角色名称" prop="roleName">
          <el-input v-model="form.roleName" placeholder="请输入角色名称" />
        </el-form-item>
        <!-- <el-form-item prop="roleKey">
          <template #label>
            <span>
              <el-tooltip content="控制器中定义的权限字符，如：@PreAuthorize(`@ss.hasRole('admin')`)"
                placement="top">
                <el-icon><question-filled /></el-icon>
              </el-tooltip>
              权限字符
            </span>
          </template>
          <el-input v-model="form.roleKey" placeholder="请输入权限字符" />
        </el-form-item> -->
        <el-form-item label="状态">
          <el-radio-group v-model="form.status">
            <el-radio label="0">正常</el-radio>
            <el-radio label="1">禁用</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="菜单权限">
          <el-checkbox v-model="menuExpand"
            @change="handleCheckedTreeExpand($event, 'menu')">展开/折叠</el-checkbox>
          <el-checkbox v-model="menuNodeAll"
            @change="handleCheckedTreeNodeAll($event, 'menu')">全选/全不选</el-checkbox>
          <el-checkbox v-model="form.menuCheckStrictly"
            @change="handleCheckedTreeConnect($event, 'menu')">上下级联动</el-checkbox>
          <el-tree class="tree-border" :data="menuOptions" show-checkbox ref="menuRef" node-key="id"
            :check-strictly="!form.menuCheckStrictly" empty-text="加载中，请稍候"
            :props="{ label: 'label', children: 'children' }"></el-tree>
        </el-form-item>
        <el-form-item label="备注">
          <el-input v-model="form.remark" type="textarea" placeholder="请输入内容"></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="cancel">取 消</el-button>
          <el-button type="primary" @click="submitForm">确 定</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Role">
import {
  addRole,
  changeRoleStatus,
  dataScope,
  delRole,
  getRole,
  listRole,
  updateRole,
  editRole,
  // deptTreeSelect,
} from "@/api/system/role";
import useUserStore from "@/store/modules/user";
const userStore = useUserStore();

import { RoleTree } from "@/api/menu";

const router = useRouter();
const { proxy } = getCurrentInstance();

const roleList = ref([]);
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");
const dateRange = ref([]);
const menuOptions = ref([]);
const menuExpand = ref(false);
const menuNodeAll = ref(false);
const deptExpand = ref(true);
const deptNodeAll = ref(false);
const deptOptions = ref([]);
const openDataScope = ref(false);
const menuRef = ref(null);
const deptRef = ref(null);

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 50,
    roleName: undefined,
    shopId: userStore.userDta.shopId,
  },
  rules: {
    roleName: [
      { required: true, message: "角色名称不能为空", trigger: "blur" },
    ],
    // roleKey: [{ required: true, message: "权限字符不能为空", trigger: "blur" }],
  },
});

const { queryParams, form, rules } = toRefs(data);

import { onMounted, onUnmounted } from "vue";

// 动态计算表格高度
const queryRef = ref(null);
const tableHeight = ref("calc(100vh - 380px)"); // 假设顶部保留200px
watch(
  () => showSearch.value,
  (newValue) => {
    if (newValue) {
      if (queryRef.value.$el.offsetHeight == 0) {
        setTimeout(() => {
          let hight = 230 + queryRef.value.$el.offsetHeight + "px";
          tableHeight.value = `calc(100vh - ` + hight + `)`;
        }, 200);
      }
    } else {
      tableHeight.value = "calc(100vh - 230px)";
    }
  },
  { deep: true }
);
function handleResize() {
  let hight = 230 + queryRef.value.$el.offsetHeight + "px";
  tableHeight.value = `calc(100vh - ` + hight + `)`;
}
onMounted(async () => {
  await nextTick();
  let hight = 230 + queryRef.value.$el.offsetHeight + "px";
  tableHeight.value = `calc(100vh - ` + hight + `)`;
  window.addEventListener("resize", handleResize);
});
// 移除事件监听器以防止内存泄漏
onUnmounted(() => {
  window.removeEventListener("resize", handleResize);
});

/** 查询角色列表 */
function getList() {
  loading.value = true;
  let userData = queryParams.value;
  let data = {
    page: userData.pageNum,
    limit: userData.pageSize,
    roleName: userData.userName,
    shopId: userData.shopId,
    roleName: userData.roleName,
  };
  listRole(data)
    .then((res) => {
      console.log(res, "这是角色列表");
      roleList.value = res.data;
      total.value = res.count;
      loading.value = false;
    })
    .catch((r) => {
      loading.value = false;
    });
}
/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}
/** 重置按钮操作 */
function resetQuery() {
  dateRange.value = [];
  proxy.resetForm("queryRef");
  handleQuery();
}
/** 删除按钮操作 */
function handleDelete(row) {
  const roleIds = row.id;
  proxy.$modal
    .confirm('是否确认删除为"' + row.roleName + '"的角色?')
    .then(function () {
      return delRole({ id: roleIds });
    })
    .then(() => {
      getList();
      proxy.$modal.msgSuccess("删除成功");
    })
    .catch(() => {});
}
/** 角色状态修改 */
function handleStatusChange(row) {
  let text = row.roleStatue === 0 ? "启用" : "停用";
  proxy.$modal
    .confirm('确认要"' + text + '""' + row.roleName + '"角色吗?')
    .then(function () {
      let dataRoleStatue = {
        id: row.id,
        state: row.roleStatue,
      };
      return changeRoleStatus(dataRoleStatue);
    })
    .then(() => {
      proxy.$modal.msgSuccess(text + "成功");
    })
    .catch(function () {
      row.roleStatue = row.roleStatue === 0 ? 1 : 0;
    });
}
/** 查询菜单树结构 */
function getMenuTreeselect() {
  RoleTree().then((response) => {
    menuOptions.value = response;
    console.log(11);
  });
}
/** 重置新增的表单以及其他数据  */
function reset() {
  if (menuRef.value != undefined) {
    menuRef.value.setCheckedKeys([]);
  }
  menuExpand.value = false;
  menuNodeAll.value = false;
  deptExpand.value = true;
  deptNodeAll.value = false;
  form.value = {
    roleId: undefined,
    roleName: undefined,
    // roleKey: undefined,
    roleSort: 0,
    status: "0",
    menuIds: [],
    deptIds: [],
    menuCheckStrictly: true,
    deptCheckStrictly: true,
    remark: undefined,
  };
  proxy.resetForm("roleRef");
}
/** 添加角色 */
function handleAdd() {
  reset();
  getMenuTreeselect();
  open.value = true;
  title.value = "添加角色";
}
/** 修改角色 */
// 必须用同步要不然 回显不出来
async function handleUpdate(row) {
  reset();
  await fetchTreeData();
  editRole({ id: row.id }).then((res) => {
    console.log(res, "这是回显");
    form.value.roleName = res.data.roleName;
    // form.value.roleKey = res.data.roleVarchar;
    form.value.status = JSON.stringify(res.data.roleStatue);
    form.value.remark = res.data.roleNote;
    form.value.id = res.data.id;
    open.value = true;
    nextTick(() => {
      let checkedKeys = res.data.ids;
      checkedKeys.forEach((v) => {
        console.log(v, 12);
        nextTick(() => {
          menuRef.value.setChecked(v, true, false);
        });
      });
      console.log(menuRef.value);
    });
    title.value = "修改角色";
  });
}
const fetchTreeData = async () => {
  await RoleTree().then((response) => {
    menuOptions.value = response;
    console.log(11);
  });
};
/** 树权限（展开/折叠）*/
function handleCheckedTreeExpand(value, type) {
  if (type == "menu") {
    let treeList = menuOptions.value;
    for (let i = 0; i < treeList.length; i++) {
      menuRef.value.store.nodesMap[treeList[i].id].expanded = value;
    }
  } else if (type == "dept") {
    let treeList = deptOptions.value;
    for (let i = 0; i < treeList.length; i++) {
      deptRef.value.store.nodesMap[treeList[i].id].expanded = value;
    }
  }
}
/** 树权限（全选/全不选） */
function handleCheckedTreeNodeAll(value, type) {
  if (type == "menu") {
    menuRef.value.setCheckedNodes(value ? menuOptions.value : []);
  } else if (type == "dept") {
    deptRef.value.setCheckedNodes(value ? deptOptions.value : []);
  }
}
/** 树权限（父子联动） */
function handleCheckedTreeConnect(value, type) {
  if (type == "menu") {
    form.value.menuCheckStrictly = value ? true : false;
  } else if (type == "dept") {
    form.value.deptCheckStrictly = value ? true : false;
  }
}
/** 所有菜单节点数据 */
function getMenuAllCheckedKeys() {
  // 目前被选中的菜单节点
  let checkedKeys = menuRef.value.getCheckedKeys();
  // 半选中的菜单节点
  let halfCheckedKeys = menuRef.value.getHalfCheckedKeys();
  checkedKeys.unshift.apply(checkedKeys, halfCheckedKeys);
  return checkedKeys;
}
/** 提交按钮 */
function submitForm() {
  proxy.$refs["roleRef"].validate((valid) => {
    if (valid) {
      form.value.menuIds = getMenuAllCheckedKeys();
      if (form.value.id != undefined) {
        let dataRole = {
          roleName: form.value.roleName,
          // roleVarchar: form.value.roleKey,
          roleStatue: form.value.status,
          roleNote: form.value.remark,
          ids: form.value.menuIds,
          shopId: queryParams.value.shopId,
          id: form.value.id,
        };
        updateRole(dataRole).then((response) => {
          proxy.$modal.msgSuccess("修改成功");
          open.value = false;
          getList();
        });
      } else {
        let dataRole = {
          roleName: form.value.roleName,
          // roleVarchar: form.value.roleKey,
          roleStatue: form.value.status,
          roleNote: form.value.remark,
          ids: form.value.menuIds,
          shopId: queryParams.value.shopId,
        };
        addRole(dataRole).then((response) => {
          proxy.$modal.msgSuccess("新增成功");
          open.value = false;
          getList();
        });
      }
    }
  });
}
/** 取消按钮 */
function cancel() {
  open.value = false;
  reset();
}
getList();
</script>
